import { useState, useEffect } from "react";

import { DatePicker, Select, Button, Table } from "antd";

import moment from "moment";
import ExportJsonExcel from "js-export-excel";

import { queryLog, getUser } from "../../serve";
import "./order.scss";
const { RangePicker } = DatePicker;
const { Option } = Select;

function Log() {
  const [logData, setLogData] = useState([]);
  const [userData, setUserData] = useState([]);
  const [serchData, setSerchData] = useState({
    page: 1,
    limit: 11,
  });
  const [total, setTotal] = useState(0);

  function disabledDate(current) {
    return current && current > moment().endOf("day");
  }

  const downloadExcel = () => {
    var option = {};
    let dataTable = [];
    logData.forEach((item) => {
      let obj = {
        userName: item.userName,
        userRole: item.userRole,
        createTime: item.createTime,
        description: item.description,
        operatingState: item.operatingState,
      };
      dataTable.push(obj);
    });
    option.fileName = "系统日志";
    option.datas = [
      {
        sheetData: dataTable,
        sheetName: "sheet",
        sheetFilter: [
          "userName",
          "userRole",
          "createTime",
          "description",
          "operatingState",
        ],
        sheetHeader: ["用户名", "用户权限", "操作时间", "操作类型", "操作状态"],
      },
    ];
    var toExcel = new ExportJsonExcel(option);
    toExcel.saveExcel();
  };

  useEffect(() => {
    queryLog(serchData).then(
      (res) =>
        res.result_code == 200 && (setLogData(res.data), setTotal(res.count))
    );
  }, [serchData]);
  useEffect(() => {
    getUser().then((res) => res.result_code == 200 && setUserData(res.data));
  }, []);

  let inputWidth = "65%";

  const columns = [
    {
      title: "用户名",
      dataIndex: "userName",
    },
    {
      title: "用户权限",
      dataIndex: "userRole",
    },
    {
      title: "日志时间",
      dataIndex: "createTime",
    },
    {
      title: "操作类型",
      dataIndex: "description",
    },
    {
      title: "操作状态",
      dataIndex: "operatingState",
    },
  ];

  return (
    <>
      <div className="top">
        <div className="top-left" style={{ float: "left" }}>
          <div>
            用户：
            <Select
              defaultValue="全部"
              style={{ width: inputWidth }}
              onChange={(val) => {
                setSerchData({
                  ...serchData,
                  username: val,
                  page: 1,
                });
              }}
            >
              <Option value="">全部</Option>
              {userData.map((item) => (
                <Option key={item.userId} value={item.username}>
                  {item.username}
                </Option>
              ))}
            </Select>
          </div>

          <div>
            操作时间：
            <RangePicker
              style={{ width: inputWidth }}
              format="YYYY/MM/DD HH:mm"
              disabledDate={disabledDate}
              onChange={(time) => {
                time == null &&
                  setSerchData({
                    ...serchData,
                    startTime: "",
                    endTime: "",
                    page: 1,
                  });
              }}
              showTime={
                ({ format: "HH:mm" },
                {
                  defaultValue: [
                    moment("00:00:00", "HH:mm:ss"),
                    moment("23:59:59", "HH:mm:ss"),
                  ],
                })
              }
              onOk={(time) => {
                if (time[0] != null && time[1] !== null) {
                  setSerchData({
                    ...serchData,
                    startTime: moment(time[0]).format("YYYY-MM-DD HH:mm:ss"),
                    endTime: moment(time[1]).format("YYYY-MM-DD HH:mm:ss"),
                    page: 1,
                  });
                }
              }}
            />
          </div>
          <div>
            操作状态：
            <Select
              defaultValue="全部"
              style={{ width: inputWidth }}
              onChange={(val) => {
                setSerchData({
                  ...serchData,
                  operatingState: val,
                  page: 1,
                });
              }}
            >
              <Option value="">全部</Option>
              <Option value="成功">成功</Option>
              <Option value="失败">失败</Option>
            </Select>
            <br />
            <br />
          </div>
        </div>
        <div className="top-right">
          <Button size="large" type="primary" onClick={downloadExcel}>
            导出数据
          </Button>
        </div>
      </div>

      <Table
        columns={columns}
        dataSource={logData}
        rowKey={(record) => record.logId}
        pagination={{
          onChange: (page, limit) => {
            setSerchData({
              ...serchData,
              page,
              limit,
            });
          },
          showTotal: (total) => `共 ${total} 条 `,
          current: serchData.page,
          position: ["bottomCenter"],
          pageSizeOptions: [30, 80, 120, 190, 300],
          defaultPageSize: 11,
          total: total, //总条数
        }}
      />
    </>
  );
}

export default Log;
